<template>
  <div>
    <el-card class="box-card">
      <!-- 面包屑 -->
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- form -->
      <el-row>
        <el-col :span="16">
          <el-form ref="form" :model="user" :rules="userRule" label-width="80px">
            <el-form-item label="标号">
              {{user.id}}
            </el-form-item>
            <el-form-item label="手机">
              {{user.mobile}}
            </el-form-item>
            <el-form-item label="媒体名称" prop="name">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍" prop="intro">
              <el-input type="textarea" v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onUpdatedProfile" :loading="updatedprofileLoading">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" :offset="2">
          <div class="demo-fit">
            <div class="block">
              <el-avatar shape="square" :size="100" fit="fit" :src="user.photo" @click.native="showSelectAvatar">
              </el-avatar>
              <input ref="avatarchange" id="avataript" type="file" hidden @change="avatarchange">
              <p><label for="avataript">点图片修改头像</label></p>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="avatardialogVisible" append-to-body @opened="onDialogOpened">
      <div class="previewContainer">
        <img ref="img" :src="previewURL">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="avatardialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onUpdatedPhone" :loading="updatedbtnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getProfileProduction,
    uploadphoto,
    uploadProfile
  } from '@/api'
  import Cropper from 'cropperjs';
  import 'cropperjs/dist/cropper.css'
  export default {
    name: 'SettingIndex',
    data() {
      return {
        avatardialogVisible: false, // 预览图片弹出层
        previewURL: '', // 预览图片url
        user: {
          mobile: '',
          name: '',
          photo: '',
          email: '',
          intro: '',
        },
        cropper: '', // 裁切图片实例
        updatedbtnLoading: false, // 图片上传loading按钮标识
        updatedprofileLoading: false, // 资料修改loading按钮标识
        userRule: {
          name: [
            { required: true, message: '必填项' , trigger: 'blur' },
            { min: 1, max:5, message: '请输入0~5位' , trigger: 'blur' },
          ],
          email: [
            { required: true, message: '必填项' , trigger: 'blur' },
          ],
          intro: [
            { required: true, message: '必填项' , trigger: 'blur' },
          ]
        }
      }
    },
    created() {
      this.getUserProfile()
    },
    mounted() {},
    methods: {
      // 修改个人资料
       onUpdatedProfile() {
        this.$refs.form.validate(async (valid) => {
            if(valid){
              this.updatedprofileLoading = true
              const {
                name,
                email,
                intro
              } = this.user
              try {
                const res = await uploadProfile({
                  name,
                  email,
                  intro
                })
                this.$message({
                  type: 'success',
                  message: '更新个人资料成功'
                })
                // 派发数据双向绑定最新的user给 header 组件更新数据属性
                this.$bus.$emit('update-user',this.user)
              } catch (e) {

              } finally {
                this.updatedprofileLoading = false
              }
            }
        })

      },
      // 获取个人信息
      async getUserProfile() {
        const res = await getProfileProduction()
        console.log(res)
        this.user = res.data
      },
      // 点击图片弹出选择图片file原生事件
      showSelectAvatar() {
        this.$refs.avatarchange.click()
      },
      // 当用户选择了新的头像时触发的事件
      avatarchange() {
        // createObjectURL方法把files图片文件对象转换为一个 blob的字符串信息
        // this.$refs.avatarchange.files[0] 等同于事件对象event里的files[0]
        let previeravatar = window.URL.createObjectURL(this.$refs.avatarchange.files[0])
        this.previewURL = previeravatar
        // console.log(previeravatar)
        // 解决选择相同文件不触发 change 事件问题
        this.$refs.avatarchange.value = ''
        // 弹出预览图片弹出窗
        this.avatardialogVisible = true
      },
      // 当 dialog 弹出层完全展示完毕时
      onDialogOpened() {
        const image = this.$refs.img
        // 能进入这个方法证明是有 cropper 实例,第二次再选图片,
        // 只需要进行替换操作即可,第一次打开是不会进入判断的
        if (this.cropper) {
          this.cropper.replace(this.previewURL)
          return
        }
        // 创建 coper 实例并且保存到全局,后续使用该实例身上的方法
        this.cropper = new Cropper(image, {
          aspectRatio: 1 / 1, // 裁剪框比例
          viewMode: 1, // 限制裁剪框不超过画布的大小。
          dragMode: 'none', // 不再创建一个新的裁剪框
          background: false, // 没有栅格格子背景
          // 裁剪框每次移动都会触发 crop 事件
          crop(event) {},
        });
      },
      // 当用户选完图片点击确定时触发的事件
      onUpdatedPhone() {
        this.updatedbtnLoading = true
        // 获取裁切的图片对象
        this.cropper.getCroppedCanvas().toBlob(async (file) => {
          // console.log(file)
          const formData = new FormData();
          formData.append('photo', file)
          try {
            // 请求提交fd
            // 请求更新用户头像
            const res = await uploadphoto(formData)
            // 关闭对话框
            this.avatardialogVisible = false
            // 更新视图展示(这里使用本地预览更加快速,不使用服务器返回的在线url,因为需要单独发送请求)
            this.user.photo = window.URL.createObjectURL(file)
            this.$message({
              type: 'success',
              message: '更新头像成功'
            })
            // console.log(res)
          } catch (e) {
            console.log(e)
          } finally {
            this.updatedbtnLoading = false
          }
        })
      }
    },
    computed: {},
    components: {}
  }
</script>
<style lang="less" scope>
  .previewContainer {
    img {
      display: block;
      max-width: 100%;
    }
  }
</style>
